//
//  NSDate+TYCreated.m
//  TYFoundation
//
//  Created by 郭艺伟 on 2019/2/28.
//

#import "NSDate+TYCreated.h"

#define D_MINUTE    60
#define D_HOUR        3600
#define D_DAY        86400
#define D_WEEK        604800
#define D_YEAR        31556926

@implementation NSDate (TYCreated)

+ (NSCalendar *)ty_currentCalendar {
    static NSCalendar *sharedCalendar = nil;
    if (!sharedCalendar)
        sharedCalendar = [NSCalendar autoupdatingCurrentCalendar];
    return sharedCalendar;
}

+ (NSDate *)ty_dateWithDaysFromNow:(NSInteger)days {
    return [[NSDate date] ty_dateByAddingDays:days];
}

+ (NSDate *)ty_dateWithDaysBeforeNow:(NSInteger)days {
    return [[NSDate date] ty_dateBySubtractingDays:days];
}

+ (NSDate *)ty_dateTomorrow {
    return [NSDate ty_dateWithDaysFromNow:1];
}

+ (NSDate *)ty_dateYesterday {
    return [NSDate ty_dateWithDaysBeforeNow:1];
}

- (NSDate *)ty_dateByAddingDays:(NSInteger)dDays {
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    [dateComponents setDay:dDays];
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:self options:0];
    return newDate;
}

- (NSDate *)ty_dateBySubtractingDays:(NSInteger)dDays {
    return [self ty_dateByAddingDays: (dDays * -1)];
}

+ (NSDate *)ty_dateWithHoursFromNow:(NSInteger)dHours {
    NSTimeInterval aTimeInterval = [[NSDate date] timeIntervalSinceReferenceDate] + D_HOUR * dHours;
    NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
    return newDate;
}

+ (NSDate *)ty_dateWithHoursBeforeNow:(NSInteger)dHours {
    NSTimeInterval aTimeInterval = [[NSDate date] timeIntervalSinceReferenceDate] - D_HOUR * dHours;
    NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
    return newDate;
}

+ (NSDate *)ty_dateWithMinutesFromNow:(NSInteger)dMinutes {
    NSTimeInterval aTimeInterval = [[NSDate date] timeIntervalSinceReferenceDate] + D_MINUTE * dMinutes;
    NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
    return newDate;
}

+ (NSDate *)ty_dateWithMinutesBeforeNow:(NSInteger)dMinutes {
    NSTimeInterval aTimeInterval = [[NSDate date] timeIntervalSinceReferenceDate] - D_MINUTE * dMinutes;
    NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
    return newDate;
}

@end
